import cookies from '@/lib/cookies';
import { Action, Module, Mutation, VuexModule } from 'vuex-module-decorators';

@Module
export default class User extends VuexModule {
  public token: string = cookies.getToken();

  public userNo: string = cookies.getUserNo();

  public userName: string = cookies.getUserName();

  public userID: string = cookies.getUserID();

  public dbName: string = cookies.getDBName();

  public connCliID: string = '';

  get UserId(): string {
    return this.userID;
  }

  get UserNo(): string {
    return this.userNo;
  }

  get UserName(): string {
    return this.userName;
  }

  get Token(): string {
    return this.token;
  }

  get DBName(): string {
    return this.dbName;
  }

  get ConnCliID(): string {
    return this.connCliID;
  }

  @Mutation
  SET_TOKEN(token: string): void {
    this.token = token;
  }

  @Mutation
  SET_USER_NO(userNo: string): void {
    this.userNo = userNo;
  }

  @Mutation
  SET_USER_NAME(userName: string): void {
    this.userName = userName;
  }

  @Mutation
  SET_USER_ID(userID: string): void {
    this.userID = userID;
  }

  @Mutation
  SET_DB_NAME(dbName: string): void {
    this.dbName = dbName;
  }

  @Mutation
  SET_CONNECT_CLIENTID(connCliID: string): void {
    this.connCliID = connCliID;
  }

  @Action({ rawError: true })
  Login(userInfo: any): any {
    const userNo: string = userInfo.userNo.trim();
    const userName: string = userInfo.userName.trim();
    return new Promise((resolve, reject) => {
      cookies.setToken(userInfo.token);
      this.context.commit('SET_TOKEN', userInfo.token);
      cookies.setUserNo(userNo);
      this.context.commit('SET_USER_NO', userNo);
      cookies.setUserName(userName);
      this.context.commit('SET_USER_NAME', userName);
      cookies.setUserID(userInfo.userID);
      this.context.commit('SET_USER_ID', userInfo.userID);
      cookies.setDBName(userInfo.dbName);
      this.context.commit('SET_DB_NAME', userInfo.dbName);
      resolve(true);
    });
  }

  @Action
  LogOut(): any {
    return new Promise((resolve, reject) => {
      this.context.commit('SET_TOKEN', '');
      this.context.commit('SET_USER_NO', '');
      this.context.commit('SET_USER_NAME', '');
      this.context.commit('SET_USER_ID', 0);
      this.context.commit('SET_DB_NAME', '');
      cookies.removeToken();
      resolve(true);
    });
  }

  @Action
  FedLogOut(): any {
    return new Promise(resolve => {
      this.context.commit('SET_TOKEN', '');
      cookies.removeToken();
      resolve(true);
    });
  }
}
